package cn.good.yan.http3;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * Http 客户端
 *
 * @author shengren.yan
 * @create 2023-05-14
 */
public class HttpTest {

    public static void main(String[] args) {
        HttpTest t = new HttpTest();
        t.tAsync();
    }

    // 异步请求
    public void tAsync(){
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(URI.create("http://goodysr.cn/")).build();
        // 响应体的处理器，处理成字符串
        HttpResponse.BodyHandler<String> stringBodyHandler = HttpResponse.BodyHandlers.ofString();
        CompletableFuture<HttpResponse<String>> future = client.sendAsync(request, stringBodyHandler);
        HttpResponse<String> response = null;
        try {
            response = future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        // 返回结果
        String body = response.body();
        System.out.println(body);
    }

    // 同步请求
    public void tSend(){
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(URI.create("http://goodysr.cn/")).build();
        // 响应体的处理器，处理成字符串
        HttpResponse.BodyHandler<String> stringBodyHandler = HttpResponse.BodyHandlers.ofString();
        // send 会阻塞等待
        HttpResponse<String> send = null;
        try {
            send = client.send(request, stringBodyHandler);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 返回结果
        String body = send.body();
        System.out.println(body);
    }
}
